import { user } from '../api'
import _ from 'lodash'
import { cookie } from 'vux'

const state = {
    power: {},
    userid: null,
    dic: null,
    dicObj: null,
    dicObjArray: null,
    debug: false,
}

const getters = {
    power: state => state.power,
    userid: state => state.userid,
    dicObj: state => state.dicObj,
    dicObjArray: state => state.dicObjArray,
    //字段数据
    status: state => {
        return {
            1: '新建',
            2: '已指派',
            3: '已结单',
            4: '已处理',
            5: '已评价',
            6: '归档'
        }
    },
}


const actions = {
    async login({ commit, state }, { userid, code }) {
        let ret = await user.login({ userid, code })
        if (!ret.success) {
            return ret
        }
        let {  userid: loginUserid } = ret.data
        
        //获取字典信息
        let retDict = await user.dict()
        let dic = retDict.data
        
        let retPower = await user.power()
        let power = retPower.data.role_powers

        //将权限数组解析成对象，便于使用
        let powerObj = {}
        power.forEach(data => {
            powerObj[data.power_code] = {
                power_text: data.power_text
            }
        })

        //将字典解析成对象，便于将id转成中文
        let dicObj = {}
        let dicObjArray = {}
        dic.forEach(data => {
            dicObj[data.id] = data.name
            if (!dicObjArray[data.type]) {
                dicObjArray[data.type] = []
            }
            dicObjArray[data.type].push({
                value: data.name,
                key: data.id
            })
        })

        commit('setPower', powerObj)
        commit('setUserid', loginUserid)
        commit('setDic', { dic, dicObj, dicObjArray })

        cookie.set('userid', loginUserid)

        return ret
    },

    async debug({ commit }, { debug }) {
        commit('setDebug', debug)
    }
}

const mutations = {
    setPower(state, power) {
        state.power = power
    },
    setUserid(state, userid) {
        state.userid = userid
    },
    setDic(state, { dic, dicObj, dicObjArray }) {
        state.dic = dic
        state.dicObj = dicObj
        state.dicObjArray = dicObjArray
    },
    setDebug(state, debug) {
        state.debug = debug
    }
}


export default {
    state,
    getters,
    actions,
    mutations
}